package main

import (
	"fmt"
	"log"
	"os"
	"path/filepath"

	"workflow-gui/internal/database"
)

func main() {
	// Get database path
	exePath, err := os.Executable()
	if err != nil {
		log.Fatalf("Failed to get executable path: %v", err)
	}

	exeDir := filepath.Dir(exePath)
	dbPath := filepath.Join(exeDir, "..", "..", "data", "workflow.db")

	// Open database
	db, err := database.Open(database.Config{Path: dbPath})
	if err != nil {
		log.Fatalf("Failed to open database: %v", err)
	}
	defer db.Close()

	fmt.Println("✅ Database opened successfully!")
	fmt.Println()

	// List all tables
	fmt.Println("📋 Tables in database:")
	fmt.Println("=" + string(make([]byte, 50)))
	
	rows, err := db.Query(`
		SELECT name FROM sqlite_master 
		WHERE type='table' 
		ORDER BY name
	`)
	if err != nil {
		log.Fatalf("Failed to query tables: %v", err)
	}
	defer rows.Close()

	tableCount := 0
	for rows.Next() {
		var tableName string
		if err := rows.Scan(&tableName); err != nil {
			log.Fatalf("Failed to scan table name: %v", err)
		}
		tableCount++
		fmt.Printf("%2d. %s\n", tableCount, tableName)
	}

	fmt.Println()
	fmt.Printf("Total tables: %d\n", tableCount)
	fmt.Println()

	// Check project_history table structure
	fmt.Println("🔍 Checking project_history table structure:")
	fmt.Println("=" + string(make([]byte, 50)))
	
	rows2, err := db.Query(`PRAGMA table_info(project_history)`)
	if err != nil {
		log.Fatalf("Failed to query table info: %v", err)
	}
	defer rows2.Close()

	fmt.Printf("%-5s %-20s %-15s %-10s %-10s %-10s\n", "CID", "Name", "Type", "NotNull", "Default", "PK")
	fmt.Println(string(make([]byte, 80)))
	
	for rows2.Next() {
		var cid int
		var name, colType string
		var notNull, pk int
		var defaultValue interface{}
		
		if err := rows2.Scan(&cid, &name, &colType, &notNull, &defaultValue, &pk); err != nil {
			log.Fatalf("Failed to scan column info: %v", err)
		}
		
		defaultStr := "NULL"
		if defaultValue != nil {
			defaultStr = fmt.Sprintf("%v", defaultValue)
		}
		
		fmt.Printf("%-5d %-20s %-15s %-10d %-10s %-10d\n", cid, name, colType, notNull, defaultStr, pk)
	}

	fmt.Println()

	// Check if there are any projects
	var projectCount int
	err = db.QueryRow("SELECT COUNT(*) FROM projects").Scan(&projectCount)
	if err != nil {
		log.Fatalf("Failed to count projects: %v", err)
	}

	fmt.Printf("📊 Current data:\n")
	fmt.Printf("   Projects: %d\n", projectCount)
	fmt.Println()
	fmt.Println("✅ Database check completed!")
}
